package com.nuaa.controller.base;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.nuaa.utils.JsonParse;


public class BaseController {
	protected void writeJson(HttpServletResponse response, Object obj) {
		this.writeJson(response, obj,"utf-8");
	}

	protected void writeJson(HttpServletResponse response, Object obj,
			String charset) {
		String json = JsonParse.getJson(obj);
		response.setContentType("text/html;charset=" + charset);
		response.setDateHeader("Expires", -10);
		PrintWriter out = null;
		try{
			out=response.getWriter();
			out.println(json);
			out.flush();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(out != null)
				out.close();
		}
	}
	public String saveFile(HttpServletRequest request,MultipartFile file){
		//System.out.println("~~~~~~~~~``");
		if(file==null || file.getOriginalFilename().isEmpty()){
			return null;
		}
		String dir = request.getServletContext().getRealPath("file");
		File director =new File(dir);    
		//如果文件夹不存在则创建    
		if  (!director .exists()  && !director .isDirectory()){       
		    director.mkdir();    
		} 
		String fileName = file.getOriginalFilename();
		String[] names = fileName.split("\\.");
		String lastNode = names[names.length-1];
		String newFileName = UUID.randomUUID()+"."+lastNode;
		String allPath = dir+"/"+newFileName;
		//System.out.println("---"+dir);
		//System.out.println(allPath);
		File upFile = new File(allPath);
		byte[] fileByte;
		try {
			fileByte = file.getBytes();
			FileCopyUtils.copy(fileByte, upFile);
			return newFileName;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
